package com.bw.ivideo.test_fragment

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.bw.ivideo.R
import com.bw.lib_common.utils.LoggerUtils
import kotlinx.coroutines.launch

class BlankFragment : Fragment() {
    private var param1: String? = null
    private var param2: String? = null
    companion object {
        const val TAG = "BlankFragment"
        @JvmStatic
        fun newInstance(param1: String, param2: String):BlankFragment{
            val fragment = BlankFragment()
            val args = Bundle()
            args.putString("ARG_PARAM1", param1)
            args.putString("ARG_PARAM2", param2)
            fragment.arguments = args
            return fragment
        }
    }

    private var isFirstLoaded = false

    private val viewModel:BlankViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val arguments = arguments
        param1 = arguments?.getString("ARG_PARAM1")
        param2 = arguments?.getString("ARG_PARAM2")
        //第一次加载
        if (!isFirstLoaded){
            loadDataFromLocal()
            isFirstLoaded = true
        }

        return inflater.inflate(R.layout.fragment_blank, container, false)
    }
    fun loadDataFromLocal(){
        viewModel.loadLocalData()
        if (true){//是否有网络
            viewModel.loadRemoteData()
        }
    }

    fun loadDataFromNet(){
        if (true){//是否有网络
            viewModel.loadRemoteData()
        }
    }

    @SuppressLint("RepeatOnLifecycleWrongUsage")
    override fun onResume() {
        super.onResume()
        LoggerUtils.d(TAG, "onResume$param1")
        //来回切换：请求网络数据
        loadDataFromNet()


        //订阅数据
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                viewModel.uiState.collect{
                    when(it){
                        is BlankViewModel.UiState.Loading -> {
                            LoggerUtils.d(TAG, "Loading")
                        }
                        is BlankViewModel.UiState.Success -> {
                            LoggerUtils.d(TAG, "Success")
                            //若是网络数据，diffUtils做局部刷新
                        }
                        is BlankViewModel.UiState.Error -> {
                            LoggerUtils.d(TAG, "Error")
                        }
                    }
                }
            }
        }
    }
    override fun onPause() {
        super.onPause()
        LoggerUtils.d(TAG, "onPause$param1")
    }

}